export default {
  clientWidth () {
    return document.documentElement.clientWidth
  },
  jsonToQueryString (json) {
    const query = []
    for (var name in json) {
      query.push(name + '=' + json[name])
    }
    return query.join('&')
  },

  toUrl (url) {
    if (url.indexOf('http') === 0) {
      window.location.href = url
    } else if (url.indexOf('//') === 0) {
      window.location.href = url.replace('//', '/index.html#/')
    } else if (url.indexOf('/') === 0) {
      window.location.href = url
    }
  },

  userAgent: {
    info: navigator.userAgent,
    is (type) {
      const _this = this
      if (type === 'WeChat') {
        type = 'MicroMessenger'
      }
      type = type.toLowerCase()
      let pattern = new RegExp(type, 'i')
      return (_this.info.search(pattern) >= 0)
    },
    isAndroid () {
      return this.is('Android')
    },
    isIOS () {
      if (this.is('iPhone') || this.is('iPod') || this.is('iPad')) {
        return true
      } else {
        return false
      }
    },
    isMI () {
      return this.is('MI ')
    },
    isWeChat () {
      return this.is('WeChat')
    }
  },

  setPageTitle (title) {
    document.title = title
    // hack for wechat
    let $body = document.getElementsByTagName('body')[0]
    let $iframe = document.createElement('iframe')

    $iframe.setAttribute('style', 'display: none;')
    $iframe.setAttribute('src', '/favicon.ico')
    $iframe.addEventListener('load', () => {
      window.setTimeout(() => {
        $body.removeChild($iframe)
      }, 100)
    })
    $body.appendChild($iframe)
  }
}
